import classnames from 'classnames'
import { useHistory } from 'react-router-dom'
import { NavBar, Search } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/types/store'
import { useDebounceFn } from 'ahooks'
import {
  clearHistory,
  clearSuggest,
  delHistory,
  getHistory,
  getSuggestionList,
} from '@/store/action/search'

const SearchPage = () => {
  const history = useHistory()
  const [keyword, setKeyword] = useState('')
  const dispatch = useDispatch()
  const [isSearching, setIsSearching] = useState(false)

  const { run: getSuggest } = useDebounceFn(
    (e: string) => {
      // console.log('搜索功能', e)
      if (!keyword) return
      dispatch(getSuggestionList(keyword))
    },
    {
      wait: 500,
    }
  )
  const onChange = (e: string) => {
    setKeyword(e)
    if (e) {
      setIsSearching(true)
      getSuggest(e)
    } else {
      setIsSearching(false)
      dispatch(clearSuggest())
    }
  }

  const suggest = useSelector((state: RootState) => state.search.suggestList)

  const highLight = (str: string) => {
    return str.replace(
      new RegExp(keyword, 'gi'),
      (match) => `<span>${match}</span>`
    )
  }
  const onSearch = (keyword: string) => {
    if (!keyword) return
    dispatch(getHistory(keyword))
    // 跳到详情页
    history.push(`/search/result?keyword=${keyword}`)
  }
  const histories = useSelector((state: RootState) => state.search.histories)
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(keyword)}>
            搜索
          </span>
        }
      >
        <Search
          placeholder="请输入关键字搜索"
          value={keyword}
          onChange={onChange}
        />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: isSearching ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={() => dispatch(clearHistory())}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => (
              <span className="history-item" key={index}>
                <span className="text-overflow" onClick={() => onSearch(item)}>
                  {item}
                </span>
                <Icon
                  type="iconbtn_essay_close"
                  onClick={(e) => {
                    e?.stopPropagation()
                    dispatch(delHistory(item))
                  }}
                />
              </span>
            ))}
          </div>
        </div>
      )}

      <div className={classnames('search-result', isSearching ? 'show' : '')}>
        {suggest.map((item, index) => (
          <div className="result-item" key={index}>
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value text-overflow"
              dangerouslySetInnerHTML={{ __html: highLight(item) }}
              onClick={() => onSearch(item)}
            ></div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default SearchPage
